package com.example.demo.producer;

import com.example.rabbitmq.starter.exception.ApiResponse;
import com.example.rabbitmq.starter.exception.BusinessException;
import com.example.rabbitmq.starter.producer.MessageProducerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 人才库更新消息生产者示例
 */
@RestController
@RequestMapping("/api/example/talent")
public class TalentUpdateProducer {

    private static final Logger log = LoggerFactory.getLogger(TalentUpdateProducer.class);

    @Autowired
    private MessageProducerFactory producerFactory;

    /**
     * 发送人才库更新消息
     *
     * @param businessId  企业ID
     * @param requestBody 请求体，包含企业信息
     * @return 发送结果
     */
    @PostMapping("/update")
    public ApiResponse<String> sendEnterpriseUpdateMessage(
            @RequestParam String businessId,
            @RequestBody @Valid Map<String, Object> requestBody) {

        // 获取人才库更新消息的生产者
        MessageProducerFactory.BusinessMessageProducer producer = producerFactory.getProducer("WChat");

        // 构建消息内容
        Map<String, Object> content = new HashMap<>(requestBody);
        content.put("timestamp", System.currentTimeMillis());
        content.put("operation", "update");

        // 发送消息
        boolean success = producer.sendMessage(businessId, content);

        if (success) {
            log.info("人才库更新消息发送成功: enterpriseId={}", businessId);
            return ApiResponse.success("人才库更新消息发送成功");
        }
        else {
            log.error("人才库更新消息发送失败: enterpriseId={}", businessId);
            throw new BusinessException("人才库更新消息发送失败，请稍后重试");
        }
    }
}